﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AutomationTools;
using AutomationTools.Procedimentos;
using AutomationTools.Procedimentos.Acao.Transformacao;
using System.Collections;
using AutomationTools.Procedimentos.Leitura;

namespace AutomationToolsSample
{
    public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();
        }

        private void btnPesquisar_Click(object sender, EventArgs e)
        {
            ProcedimentoController controller = new ProcedimentoController(
                new Request("http://ark42.com/mtg/pricelist.php", null, Request.EnumFormMethod.POST),
                new RegexParseObject<ResultadoArk>()
            );


            ParametrosRequest nill = null;
            dynamic c = new Contexto();
            c.Uri = "http://ark42.com/mtg/pricelist.php";
            c.Method = "POST";
            c.Parametros = nill;

            var rets = (ResultadoArk)controller.ExecutarProcedimentos(c);
            label1.Text = "";
            var ret = rets.Categorias.ToList().Select(x => new Categoria()
                {
                    Nome = x.Nome,
                    Cards = x.Cards.Where(y => y != null
                        && y.Nome != null
                        && y.Nome.ToUpper().Contains(txtPesquisar.Text.ToUpper())).ToArray()
                }
            ).Where(x => x.Cards.Length > 0);

            foreach (var item in ret)
            {
                label1.Text += "*** " + item.Nome + " ***" + Environment.NewLine;
                foreach (var cards in item.Cards)
                {
                    label1.Text += cards.Nome + "-->" + cards.Preco + Environment.NewLine;
                }
                label1.Text += Environment.NewLine;
            }
        }


        [CanRegexParse]
        public class ResultadoArk
        {
            [RegexParse(@"<table cellspacing=""0"" width=""100%"">.*?</table>", IsArray = true)]
            public Categoria[] Categorias { get; set; }
        }

        [CanRegexParse]
        public class Categoria
        {
            [RegexParse(@"<th.*?><img.*?>(.*?)</th>", Grupo = 1)]
            public string Nome { get; set; }
            [RegexParse(@"<tr>.*?</tr>", IsArray = true)]
            public CartaArk[] Cards { get; set; }
        }

        [CanRegexParse]
        public class CartaArk
        {
            [RegexParse(@"onmouseout=""tipclear\(\)"">(?:<.*?>.*?<.*?>)?(.*?)</a>", Index = 0, Grupo = 1)]
            public string Nome { get; set; }
            [RegexParse(@"onmouseout=""tipclear\(\)"">(?:<.*?>.*?<.*?>)?(.*?)</a>", Index = 1, Grupo = 1)]
            public string Preco { get; set; }
        }
    }
}